<template>
  <div class="dashboard-container">
    <!-- 3D粒子背景 -->
    <ParticleBackground />
    
    <!-- 主标题 -->
    <header class="dashboard-header">
      <div class="header-content">
        <div class="header-left">
          <div class="title-decoration">
            <div class="decoration-line"></div>
          </div>
          <h1 class="main-title">
            <span class="title-icon">🚀</span>
            智慧电商数据大屏
          </h1>
          <p class="subtitle">实时监控 · 数据驱动 · 智能分析</p>
        </div>
        
        <div class="header-right">
          <!-- 实时状态指示器 -->
          <div class="status-indicators">
            <div class="status-card system-status">
              <div class="status-icon">🟢</div>
              <div class="status-info">
                <div class="status-label">系统状态</div>
                <div class="status-value">运行正常</div>
              </div>
            </div>
            
            <div class="status-card network-status" :class="networkStatusClass">
              <div class="status-icon">📡</div>
              <div class="status-info">
                <div class="status-label">网络状态</div>
                <div class="status-value">{{ networkStatus }}ms</div>
              </div>
            </div>
            
            <div class="status-card online-users">
              <div class="status-icon">👥</div>
              <div class="status-info">
                <div class="status-label">在线用户</div>
                <div class="status-value">{{ onlineUsers.toLocaleString() }}</div>
              </div>
            </div>
          </div>
          
          <!-- 时间日期区域 -->
          <div class="time-section">
            <div class="current-time">{{ currentTime }}</div>
            <div class="date-display">{{ currentDate }}</div>
            <div class="week-display">星期{{ weekDay }}</div>
          </div>
          
          <!-- 快速操作区域 -->
          <div class="quick-actions">
            <button class="action-btn refresh-btn" @click="refreshData" title="刷新数据">
              <span class="btn-icon">🔄</span>
            </button>
            <button class="action-btn export-btn" @click="exportData" title="导出报表">
              <span class="btn-icon">📊</span>
            </button>
            <button class="action-btn fullscreen-btn" @click="toggleFullscreen" title="全屏模式">
              <span class="btn-icon">⛶</span>
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- 动态弹幕区域 -->
    <section class="barrage-section">
      <div class="barrage-container">
        <div class="barrage-track">
          <div
            v-if="currentBarrage"
            ref="barrageRef"
            class="barrage-message"
            :class="currentBarrage.type"
            :key="barrageKey"
          >
            <span class="message-icon">{{ currentBarrage.icon }}</span>
            <span class="message-text">{{ currentBarrage.text }}</span>
            <span class="message-time">{{ currentBarrage.time }}</span>
          </div>
        </div>
      </div>
    </section>

    <!-- 核心指标卡片区域 -->
    <section class="metrics-section">
      <div class="metrics-grid">
        <DataCard
          v-for="(metric, index) in coreMetrics"
          :key="index"
          :title="metric.title"
          :value="metric.value"
          :unit="metric.unit"
          :prefix="metric.prefix"
          :suffix="metric.suffix"
          :decimals="metric.decimals"
          :icon="metric.icon"
          :icon-color="metric.iconColor"
          :trend="metric.trend"
          :animated="true"
          :style="{ animationDelay: index * 100 + 'ms' }"
        />
      </div>
    </section>

    <!-- 主要图表区域 -->
    <section class="charts-section">
      <div class="charts-grid">
        <!-- 销售数据分析 -->
        <div class="chart-item chart-large">
          <SalesDashboard />
        </div>

        <!-- 实时用户分布 -->
        <div class="chart-item chart-medium">
          <div class="map-container">
            <div class="map-header">
              <h3 class="section-title">实时用户分布</h3>
              <div class="map-stats">
                <div class="stat-item">
                  <span class="stat-label">在线用户</span>
                  <AnimatedCounter :value="89240" suffix="人" class="stat-value" />
                </div>
                <div class="stat-item">
                  <span class="stat-label">活跃城市</span>
                  <AnimatedCounter :value="156" suffix="个" class="stat-value" />
                </div>
              </div>
            </div>
            <div class="map-chart">
              <RealTimeMap />
            </div>
          </div>
        </div>
        
        <!-- 实时订单流 -->
        <div class="chart-item chart-small">
          <RealTimeOrders />
        </div>

        <!-- 系统监控 (对齐销售概览) -->
        <div class="chart-item chart-large">
          <SystemMonitor />
        </div>
        
        <!-- 销售趋势 (对齐实时用户分布) -->
        <div class="chart-item chart-medium">
          <div class="chart-container">
            <div class="chart-header">
              <h3 class="chart-title">销售趋势分析</h3>
              <div class="chart-indicators">
                <span
                  class="indicator"
                  :class="{ active: trendType === 'day' }"
                  @click="changeTrendType('day')"
                >日</span>
                <span
                  class="indicator"
                  :class="{ active: trendType === 'week' }"
                  @click="changeTrendType('week')"
                >周</span>
                <span
                  class="indicator"
                  :class="{ active: trendType === 'month' }"
                  @click="changeTrendType('month')"
                >月</span>
              </div>
            </div>
            <div :ref="setTrendChartRef" class="chart-content"></div>
          </div>
        </div>
        
        <!-- 商品分类占比 (对齐实时订单流) -->
        <div class="chart-item chart-small">
          <div class="chart-container">
            <div class="chart-header">
              <h3 class="chart-title">商品分类占比</h3>
            </div>
            <div :ref="setCategoryChartRef" class="chart-content"></div>
          </div>
        </div>
        
        <!-- 热销商品排行 -->
        <div class="chart-item chart-extra-small">
          <div class="chart-container">
            <div class="chart-header">
              <h3 class="chart-title">热销商品TOP10</h3>
              <div class="pagination-dots">
                <span 
                  v-for="(_, idx) in totalPages" 
                  :key="idx"
                  class="dot" 
                  :class="{ active: idx === currentPage }"
                ></span>
              </div>
            </div>
            <div class="ranking-list">
              <div 
                v-for="(item, index) in currentPageProducts" 
                :key="`${currentPage}-${index}`"
                class="ranking-item fade-in"
                :style="{ animationDelay: index * 100 + 'ms' }"
              >
                <div class="rank-number" :class="`rank-${getRealRank(index)}`">
                  {{ getRealRank(index) }}
                </div>
                <div class="product-info">
                  <div class="product-name">{{ item.name }}</div>
                  <div class="product-meta">
                    <span class="product-category">{{ item.category }}</span>
                    <span class="product-sales">{{ item.sales }}件</span>
                  </div>
                  <div class="product-growth" :class="item.growth > 10 ? 'high-growth' : 'normal-growth'">
                    ↗ +{{ item.growth }}%
                  </div>
                </div>
                <div class="sales-metrics">
                  <div class="sales-bar">
                    <div 
                      class="bar-fill" 
                      :style="{ width: (item.sales / maxSales * 100) + '%' }"
                    ></div>
                  </div>
                  <div class="revenue-text">¥{{ (item.revenue / 10000).toFixed(1) }}万</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 用户活跃度 -->
        <div class="chart-item chart-extra-small">
          <div class="chart-container">
            <div class="chart-header">
              <h3 class="chart-title">用户活跃度</h3>
            </div>
            <div :ref="setUserActivityChartRef" class="chart-content"></div>
          </div>
        </div>
        
        <!-- 实时交易监控 -->
        <div class="chart-item chart-extra-small">
          <RealtimeTrading />
        </div>

        <!-- 营收仪表盘 -->
        <div class="chart-item chart-extra-small">
          <RevenueDashboard />
        </div>
      </div>
    </section>

    <!-- 底部数据流 -->
    <section class="data-stream-section">
      <div class="stream-container">
        <div class="stream-title">实时数据流</div>
        <div class="stream-content">
          <div class="stream-item" v-for="(stream, index) in dataStreams" :key="index">
            <span class="stream-label">{{ stream.label }}</span>
            <span class="stream-value">{{ stream.value }}</span>
            <span class="stream-unit">{{ stream.unit }}</span>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick, watchEffect, watch } from 'vue'
import * as echarts from 'echarts'
import { gsap } from 'gsap'
import ParticleBackground from '../components/ParticleBackground.vue'
import DataCard from '../components/DataCard.vue'
import SalesDashboard from '../components/SalesDashboard.vue'
import RealTimeMap from '../components/RealTimeMap.vue'
import AnimatedCounter from '../components/AnimatedCounter.vue'
import RealTimeOrders from '../components/RealTimeOrders.vue'
import SystemMonitor from '../components/SystemMonitor.vue'
import RealtimeTrading from '../components/RealtimeTrading.vue'
import RevenueDashboard from '../components/RevenueDashboard.vue'
import { 
  coreMetrics as mockCoreMetrics, 
  realTimeData, 
  hotProducts as mockHotProducts, 
  categoryData, 
  hourlyTrend, 
  weeklyActivity,
  updateRealTimeData,
  UPDATE_INTERVALS
} from '../mock/dashboardData.js'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

// 响应式数据
const currentTime = ref(new Date().toLocaleTimeString())
const currentDate = ref(new Date().toLocaleDateString())
const weekDay = ref(getWeekDay())
const networkStatus = ref(Math.floor(Math.random() * 50) + 20) // 模拟网络延迟 20-70ms
const onlineUsers = ref(89240 + Math.floor(Math.random() * 1000)) // 模拟在线用户数
const trendChartRef = ref(null)
const categoryChartRef = ref(null)
const userActivityChartRef = ref(null)

// 图表实例
let trendChart = null
let categoryChart = null
let userActivityChart = null
let updateTimer = null

// 图表初始化标记
const chartsInitialized = ref(false)

// ref回调函数，确保元素挂载后立即初始化
const setTrendChartRef = async (el) => {
  if (el && !trendChart) {
    console.log('销售趋势图表元素已挂载，立即初始化...')
    await nextTick();
    await initTrendChart(el);
  }
}

const setCategoryChartRef = async (el) => {
  if (el && !categoryChart) {
    console.log('分类占比图表元素已挂载，立即初始化...')
    await nextTick();
    await initCategoryChart(el);
  }
}

const setUserActivityChartRef = async (el) => {
  if (el && !userActivityChart) {
    console.log('用户活跃度图表元素已挂载，立即初始化...')
    await nextTick();
    await initUserActivityChart(el);
  }
}

// 核心指标数据
const coreMetrics = ref([
  {
    title: '今日销售额',
    value: mockCoreMetrics.todaySales.value,
    unit: '元',
    prefix: '¥',
    decimals: 0,
    icon: 'Money',
    iconColor: '#00f0ff',
    trend: { direction: mockCoreMetrics.todaySales.trend, text: `+${mockCoreMetrics.todaySales.change}%` }
  },
  {
    title: '订单数量',
    value: mockCoreMetrics.orders.value,
    unit: '单',
    decimals: 0,
    icon: 'ShoppingCart',
    iconColor: '#00ff9d',
    trend: { direction: mockCoreMetrics.orders.trend, text: `+${mockCoreMetrics.orders.change}%` }
  },
  {
    title: '活跃用户',
    value: mockCoreMetrics.activeUsers.value,
    unit: '人',
    decimals: 0,
    icon: 'User',
    iconColor: '#ffa502',
    trend: { direction: mockCoreMetrics.activeUsers.trend, text: `+${mockCoreMetrics.activeUsers.change}%` }
  },
  {
    title: '转化率',
    value: mockCoreMetrics.conversionRate.value,
    unit: '%',
    decimals: 2,
    icon: 'TrendCharts',
    iconColor: '#ff4757',
    trend: { direction: mockCoreMetrics.conversionRate.trend, text: `+${mockCoreMetrics.conversionRate.change}%` }
  },
  {
    title: '客单价',
    value: mockCoreMetrics.avgOrderValue.value,
    unit: '元',
    prefix: '¥',
    decimals: 1,
    icon: 'Wallet',
    iconColor: '#7bed9f',
    trend: { direction: mockCoreMetrics.avgOrderValue.trend, text: `${mockCoreMetrics.avgOrderValue.change}%` }
  }
])

// 热销商品数据
const hotProducts = ref(mockHotProducts)

// 分页相关数据
const currentPage = ref(0)
const itemsPerPage = 8
const pageChangeInterval = 5000 // 5秒切换一页
let pageTimer = null

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(hotProducts.value.length / itemsPerPage)
})

const currentPageProducts = computed(() => {
  const start = currentPage.value * itemsPerPage
  const end = start + itemsPerPage
  return hotProducts.value.slice(start, end)
})

const getRealRank = (index) => {
  return currentPage.value * itemsPerPage + index + 1
}

const maxSales = computed(() => {
  return Math.max(...hotProducts.value.map(item => item.sales))
})

// 网络状态样式计算
const networkStatusClass = computed(() => {
  if (networkStatus.value <= 30) return 'network-good'
  if (networkStatus.value <= 60) return 'network-normal'
  return 'network-poor'
})

// 实时数据流
const dataStreams = ref([
  { label: 'PV', value: realTimeData.pv.toLocaleString(), unit: '/h' },
  { label: 'UV', value: realTimeData.uv.toLocaleString(), unit: '/h' },
  { label: '订单', value: realTimeData.orders.toLocaleString(), unit: '/天' },
  { label: '支付', value: `${realTimeData.revenue}M`, unit: '元/天' },
  { label: '退款', value: `${realTimeData.refundRate}%`, unit: '率' }
])

// 弹幕消息数据
const barrageMessages = [
  { icon: '🎉', text: '恭喜！北京用户刚刚下单iPhone 15 Pro Max', type: 'success', time: '刚刚' },
  { icon: '💰', text: '销售额突破500万！今日业绩再创新高', type: 'achievement', time: '10分钟前' },
  { icon: '🔥', text: '热销预警：AirPods Pro 2库存告急', type: 'warning', time: '15分钟前' },
  { icon: '📈', text: '用户活跃度上升15%，转化率持续优化', type: 'info', time: '20分钟前' },
  { icon: '🌟', text: '上海地区订单量激增，排名跃居第一', type: 'success', time: '25分钟前' },
  { icon: '⚡', text: '系统处理能力达到峰值，运行状态良好', type: 'info', time: '30分钟前' },
  { icon: '🎯', text: '新用户注册量突破1000人次', type: 'success', time: '35分钟前' },
  { icon: '💎', text: 'VIP客户消费金额同比增长230%', type: 'achievement', time: '40分钟前' },
  { icon: '🚀', text: '移动端访问量占比达到76%', type: 'info', time: '45分钟前' },
  { icon: '⭐', text: '客户满意度评分4.9分，服务质量优秀', type: 'success', time: '50分钟前' },
  { icon: '🎊', text: '双11活动预热开始，流量激增300%', type: 'event', time: '55分钟前' },
  { icon: '📊', text: '数据分析显示：用户停留时间增加40%', type: 'info', time: '1小时前' }
]

// 当前弹幕
const currentBarrage = ref(barrageMessages[0])
const barrageKey = ref(0)
const barrageRef = ref(null)
let barrageIndex = 0
let barrageTimer = null
let barrageDuration = 8000 // 默认初始值

const showBarrage = () => {
  clearTimeout(barrageTimer)
  barrageTimer = setTimeout(() => {
    barrageIndex = (barrageIndex + 1) % barrageMessages.length
    currentBarrage.value = barrageMessages[barrageIndex]
    barrageKey.value++ // 每次切换强制刷新 DOM
    showBarrage()
  }, barrageDuration)
}

// 监听 currentBarrage，每次切换后执行动画
watch(currentBarrage, async () => {
  console.log('[弹幕watch] currentBarrage 切换:', currentBarrage.value)
  await nextTick()
  const el = barrageRef.value
  console.log('[弹幕watch] barrageRef.value:', el)
  if (!el) return
  const trackWidth = el.parentNode.offsetWidth
  const msgWidth = el.offsetWidth
  const minDuration = 5 // minDuration 是最慢速度的下限（比如 5 秒），可以适当调小或调大。
  const speed = 130     // speed 数值越大，滚动越快（比如 200 比 100 快一倍）
  const duration = Math.max(minDuration, (trackWidth + msgWidth) / speed)
  console.log('[弹幕watch] trackWidth:', trackWidth, 'msgWidth:', msgWidth, 'duration:', duration)
  el.style.transition = 'none'
  el.style.transform = `translateX(-${msgWidth}px)`
  console.log('[弹幕watch] 初始 transform:', el.style.transform)
  void el.offsetWidth
  el.style.transition = `transform ${duration}s linear`
  el.style.transform = `translateX(${trackWidth}px)`
  console.log('[弹幕watch] 启动动画 transform:', el.style.transform, 'transition:', el.style.transition)
  barrageDuration = duration * 1000
})

onMounted(() => {
  console.log('组件已挂载')
  startTimeUpdate()
  startDataAnimation()
  startRealTimeUpdate()
  startPagination()

  
  // 添加全局resize监听
  const handleResize = () => {
    console.log('窗口尺寸变化，调整图表尺寸')
    // 延迟执行确保DOM更新完成
    setTimeout(() => {
      trendChart?.resize()
      categoryChart?.resize()
      userActivityChart?.resize()
    }, 100)
  }
  
  // 监听窗口尺寸变化
  window.addEventListener('resize', handleResize)
  
  // 监听显示器变化（当窗口移动到不同显示器时）
  const handleDisplayChange = () => {
    console.log('检测到显示器变化，重新调整布局')
    setTimeout(() => {
      trendChart?.resize()
      categoryChart?.resize()
      userActivityChart?.resize()
      // 强制重新计算网格布局
      document.documentElement.style.setProperty('--viewport-width', window.innerWidth + 'px')
      document.documentElement.style.setProperty('--viewport-height', window.innerHeight + 'px')
    }, 200)
  }
  
  // 使用 MutationObserver 监听媒体查询变化
  if (window.matchMedia) {
    const mediaQueries = [
      '(min-width: 2560px)',
      '(min-width: 1920px) and (max-width: 2559px)',
      '(min-width: 1400px) and (max-width: 1919px)',
      '(min-width: 1200px) and (max-width: 1399px)',
      '(min-width: 992px) and (max-width: 1199px)',
      '(min-width: 768px) and (max-width: 991px)',
      '(max-width: 767px)'
    ]
    
    mediaQueries.forEach(query => {
      const mq = window.matchMedia(query)
      mq.addListener(handleDisplayChange)
    })
  }
  
  // 初始设置viewport变量
  document.documentElement.style.setProperty('--viewport-width', window.innerWidth + 'px')
  document.documentElement.style.setProperty('--viewport-height', window.innerHeight + 'px')
  
  // 初始化弹幕
  currentBarrage.value = barrageMessages[0]
  console.log('弹幕系统启动，首条弹幕:', currentBarrage.value.text)
  
  // 启动环形指示器定时器
  // ringTimer = setInterval(updateRingIndicators, 3000) // 3秒更新一次指示器状态

  showBarrage()
})

onUnmounted(() => {
  // 清理图表
  if (trendChart) trendChart.dispose()
  if (categoryChart) categoryChart.dispose()
  if (userActivityChart) userActivityChart.dispose()
  
  // 清理定时器
  if (updateTimer) clearInterval(updateTimer)
  if (pageTimer) clearInterval(pageTimer)
  if (barrageTimer) clearInterval(barrageTimer)
  // if (ringTimer) clearInterval(ringTimer)
  
  // 清理事件监听器
  window.removeEventListener('resize', () => {})
  
  // 清理媒体查询监听器
  if (window.matchMedia) {
    const mediaQueries = [
      '(min-width: 2560px)',
      '(min-width: 1920px) and (max-width: 2559px)',
      '(min-width: 1400px) and (max-width: 1919px)',
      '(min-width: 1200px) and (max-width: 1399px)',
      '(min-width: 992px) and (max-width: 1199px)',
      '(min-width: 768px) and (max-width: 991px)',
      '(max-width: 767px)'
    ]
    
    mediaQueries.forEach(query => {
      const mq = window.matchMedia(query)
      mq.removeListener(() => {})
    })
  }
})

const startTimeUpdate = () => {
  setInterval(() => {
    currentTime.value = new Date().toLocaleTimeString()
    currentDate.value = new Date().toLocaleDateString()
    weekDay.value = getWeekDay()
  }, 1000)
}

const initCharts = async () => {
  console.log('开始初始化图表...')
  try {
    // 简单直接的初始化方式
    setTimeout(async () => {
      // 初始化销售趋势图
      if (trendChartRef.value) {
        console.log('初始化销售趋势图表...')
        if (trendChart) {
          trendChart.dispose()
        }
        trendChart = echarts.init(trendChartRef.value)
        const type = trendType.value;
        const data = trendDataMap[type];
        const xAxis = trendXAxisMap[type];
        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(15, 52, 96, 0.9)',
            borderColor: '#00f0ff',
            borderWidth: 1,
            textStyle: { color: '#ffffff' }
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '10%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xAxis, // 动态横坐标
            axisLine: { lineStyle: { color: '#00f0ff' } },
            axisLabel: { color: '#7ee9ff' }
          },
          yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#00f0ff' } },
            axisLabel: {
              color: '#7ee9ff',
              formatter: '¥{value}'
            },
            splitLine: { lineStyle: { color: 'rgba(0, 240, 255, 0.1)' } }
          },
          series: [{
            data: data,
            type: 'line',
            smooth: true,
            lineStyle: { color: '#00f0ff', width: 3 },
            itemStyle: { color: '#00f0ff' },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(0, 240, 255, 0.3)' },
                  { offset: 1, color: 'rgba(0, 240, 255, 0)' }
                ]
              }
            }
          }]
        };
        await nextTick();
        trendChart.setOption(option, { notMerge: true });
        await nextTick();
        trendChart.resize();
        console.log('销售趋势图表初始化完成');
      }
      // 初始化分类占比图
      if (categoryChartRef.value) {
        console.log('初始化分类占比图表...')
        if (categoryChart) {
          categoryChart.dispose()
        }
        categoryChart = echarts.init(categoryChartRef.value)
        const categoryOption = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(15, 52, 96, 0.9)',
            borderColor: '#00f0ff',
            borderWidth: 1,
            textStyle: { color: '#ffffff' }
          },
          legend: {
            orient: 'horizontal',
            bottom: '5%',
            left: 'center',
            textStyle: { color: '#ffffff' }
          },
          series: [{
            type: 'pie',
            radius: ['35%', '65%'],
            center: ['50%', '40%'],
            data: [
              { value: 35, name: '服装', itemStyle: { color: '#00f0ff' } },
              { value: 28, name: '数码', itemStyle: { color: '#00ff9d' } },
              { value: 20, name: '食品', itemStyle: { color: '#ffa502' } },
              { value: 17, name: '其他', itemStyle: { color: '#ff4757' } }
            ],
            label: {
              show: true,
              color: '#ffffff',
              formatter: '{b}: {c}%'
            }
          }]
        };
        await nextTick();
        categoryChart.setOption(categoryOption, { notMerge: true });
        await nextTick();
        categoryChart.resize();
        console.log('分类占比图表初始化完成')
      }
      // 初始化用户活跃度图
      if (userActivityChartRef.value) {
        console.log('初始化用户活跃度图表...')
        if (userActivityChart) {
          userActivityChart.dispose()
        }
        userActivityChart = echarts.init(userActivityChartRef.value)
        const userActivityOption = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(15, 52, 96, 0.9)',
            borderColor: '#00f0ff',
            borderWidth: 1,
            textStyle: { color: '#ffffff' }
          },
          legend: {
            data: ['PV', 'UV'],
            textStyle: { color: '#ffffff' },
            top: '5%'
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '10%',
            top: '20%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            axisLine: { lineStyle: { color: '#00f0ff' } },
            axisLabel: { color: '#7ee9ff' }
          },
          yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#00f0ff' } },
            axisLabel: { color: '#7ee9ff' },
            splitLine: { lineStyle: { color: 'rgba(0, 240, 255, 0.1)' } }
          },
          series: [
            {
              name: 'PV',
              data: [8200, 9100, 7800, 9500, 10200, 8800, 7600],
              type: 'bar',
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: '#00f0ff' },
                    { offset: 1, color: 'rgba(0, 240, 255, 0.1)' }
                  ]
                }
              }
            },
            {
              name: 'UV',
              data: [3200, 3800, 3100, 4200, 4800, 3600, 3000],
              type: 'bar',
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: '#00ff9d' },
                    { offset: 1, color: 'rgba(0, 255, 157, 0.1)' }
                  ]
                }
              }
            }
          ]
        }
        
        userActivityChart.setOption(userActivityOption, { notMerge: true });
        await nextTick();
        userActivityChart.resize();
        console.log('用户活跃度图表初始化完成')
      }
      
      // 添加窗口resize监听
      const handleResize = () => {
        trendChart?.resize()
        categoryChart?.resize()
        userActivityChart?.resize()
      }
      
      window.removeEventListener('resize', handleResize)
      window.addEventListener('resize', handleResize)
      
      console.log('所有图表初始化完成')
      
    }, 100) // 简短延迟即可
    
  } catch (error) {
    console.error('图表初始化失败:', error)
  }
}

const startDataAnimation = () => {
  // 启动GSAP动画
  gsap.fromTo(".metrics-grid .data-card", {
    y: 50,
    opacity: 0
  }, {
    y: 0,
    opacity: 1,
    duration: 0.8,
    stagger: 0.1,
    ease: "power2.out"
  })

  gsap.fromTo(".charts-grid .chart-item", {
    scale: 0.9,
    opacity: 0
  }, {
    scale: 1,
    opacity: 1,
    duration: 1,
    stagger: 0.2,
    ease: "power2.out",
    delay: 0.5
  })
}

const startRealTimeUpdate = () => {
  updateTimer = setInterval(() => {
    const updatedData = updateRealTimeData()
    
    // 更新实时数据流
    dataStreams.value = [
      { label: 'PV', value: updatedData.realTimeData.pv.toLocaleString(), unit: '/h' },
      { label: 'UV', value: updatedData.realTimeData.uv.toLocaleString(), unit: '/h' },
      { label: '订单', value: updatedData.realTimeData.orders.toLocaleString(), unit: '/天' },
      { label: '支付', value: `${updatedData.realTimeData.revenue}M`, unit: '元/天' },
      { label: '退款', value: `${updatedData.realTimeData.refundRate}%`, unit: '率' }
    ]
    
    // 更新核心指标
    coreMetrics.value[0].value = updatedData.coreMetrics.todaySales.value
    coreMetrics.value[1].value = updatedData.coreMetrics.orders.value
    coreMetrics.value[2].value = updatedData.coreMetrics.activeUsers.value
    coreMetrics.value[3].value = updatedData.coreMetrics.conversionRate.value
    coreMetrics.value[4].value = updatedData.coreMetrics.avgOrderValue.value
    
    // 更新销售趋势图表
    updateTrendChart()
    
    // 更新用户活跃度图表
    updateActivityChart()
    
    // 更新状态指示器
    networkStatus.value = Math.floor(Math.random() * 30) + 15 // 15-45ms
    onlineUsers.value = 89240 + Math.floor(Math.random() * 2000 - 1000) // ±1000 变化
    
    // 添加数据更新的微动画
    gsap.to(".stream-item", {
      scale: 1.05,
      duration: 0.2,
      yoyo: true,
      repeat: 1,
      ease: "power2.inOut"
    })
    
        // 状态卡片闪烁动画
    gsap.to(".status-card", {
      backgroundColor: "rgba(0, 240, 255, 0.1)",
      duration: 0.3,
      yoyo: true,
      repeat: 1,
      ease: "power2.inOut"
    })
    
    // 环形指示器闪烁效果
    // gsap.to(".ring-content", {
    //   boxShadow: "0 0 30px rgba(0, 240, 255, 0.4), inset 0 0 30px rgba(0, 240, 255, 0.2)",
    //   duration: 0.3,
    //   yoyo: true,
    //   repeat: 1,
    //   ease: "power2.inOut"
    // })
    
  }, UPDATE_INTERVALS.REAL_TIME)
}

// 更新趋势图表数据
const updateTrendChart = async () => {
  if (!trendChart) return;
  const type = trendType.value;
  const data = trendDataMap[type];
  const xAxis = trendXAxisMap[type];
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(15, 52, 96, 0.9)',
      borderColor: '#00f0ff',
      borderWidth: 1,
      textStyle: { color: '#ffffff' }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      data: xAxis,
      type: 'category',
      axisLine: { lineStyle: { color: '#00f0ff' } },
      axisLabel: { color: '#7ee9ff' }
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#00f0ff' } },
      axisLabel: {
        color: '#7ee9ff',
        formatter: '¥{value}'
      },
      splitLine: { lineStyle: { color: 'rgba(0, 240, 255, 0.1)' } }
    },
    series: [{
      data: data,
      type: 'line',
      smooth: true,
      lineStyle: { color: '#00f0ff', width: 3 },
      itemStyle: { color: '#00f0ff' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(0, 240, 255, 0.3)' },
            { offset: 1, color: 'rgba(0, 240, 255, 0)' }
          ]
        }
      }
    }]
  };
  await nextTick();
  trendChart.setOption(option, { notMerge: true });
  // 添加图表更新动画
  gsap.fromTo(".chart-content", {
    opacity: 0.8
  }, {
    opacity: 1,
    duration: 0.5,
    ease: "power2.out"
  });
}

// 更新用户活跃度图表
const updateActivityChart = () => {
  if (!userActivityChart) return
  
  // 生成新的活跃度数据
  const newActivityData = weeklyActivity.map(item => ({
    ...item,
    pv: Math.max(1000, item.pv + (Math.random() - 0.5) * 2000),
    uv: Math.max(500, item.uv + (Math.random() - 0.5) * 1000)
  }))
  
  const option = {
    series: [
      {
        name: 'PV',
        data: newActivityData.map(item => Math.round(item.pv)),
        type: 'bar',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: '#00f0ff' },
              { offset: 1, color: 'rgba(0, 240, 255, 0.1)' }
            ]
          }
        }
      },
      {
        name: 'UV',
        data: newActivityData.map(item => Math.round(item.uv)),
        type: 'bar',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: '#00ff9d' },
              { offset: 1, color: 'rgba(0, 255, 157, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  
  userActivityChart.setOption(option, { notMerge: true })
}

const debugCharts = () => {
  console.log('=== 图表状态检查 ===')
  console.log('图表实例:', {
    trendChart: !!trendChart,
    categoryChart: !!categoryChart, 
    userActivityChart: !!userActivityChart
  })
  
  // 作为备用的强制初始化
  initCharts()
}

// 独立的图表初始化函数
const initTrendChart = async (element) => {
  try {
    if (trendChart) {
      trendChart.dispose()
    }
    trendChart = echarts.init(element)
    const type = trendType.value;
    const data = trendDataMap[type];
    const xAxis = trendXAxisMap[type];
    const option = {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(15, 52, 96, 0.9)',
        borderColor: '#00f0ff',
        borderWidth: 1,
        textStyle: { color: '#ffffff' }
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '10%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxis, // 动态横坐标
        axisLine: { lineStyle: { color: '#00f0ff' } },
        axisLabel: { color: '#7ee9ff' }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#00f0ff' } },
        axisLabel: {
          color: '#7ee9ff',
          formatter: '¥{value}'
        },
        splitLine: { lineStyle: { color: 'rgba(0, 240, 255, 0.1)' } }
      },
      series: [{
        data: data,
        type: 'line',
        smooth: true,
        lineStyle: { color: '#00f0ff', width: 3 },
        itemStyle: { color: '#00f0ff' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(0, 240, 255, 0.3)' },
              { offset: 1, color: 'rgba(0, 240, 255, 0)' }
            ]
          }
        }
      }]
    };
    await nextTick();
    trendChart.setOption(option, { notMerge: true });
    await nextTick();
    trendChart.resize();
    console.log('销售趋势图表初始化成功');
  } catch (error) {
    console.error('销售趋势图表初始化失败:', error);
  }
};

const initCategoryChart = async (element) => {
  try {
    if (categoryChart) {
      categoryChart.dispose()
    }
    
    categoryChart = echarts.init(element)
    
    const categoryOption = {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(15, 52, 96, 0.9)',
        borderColor: '#00f0ff',
        borderWidth: 1,
        textStyle: { color: '#ffffff' }
      },
      legend: {
        orient: 'horizontal',
        bottom: '5%',
        left: 'center',
        textStyle: { color: '#ffffff' }
      },
      series: [{
        type: 'pie',
        radius: ['35%', '65%'],
        center: ['50%', '40%'],
        data: [
          { value: 35, name: '服装', itemStyle: { color: '#00f0ff' } },
          { value: 28, name: '数码', itemStyle: { color: '#00ff9d' } },
          { value: 20, name: '食品', itemStyle: { color: '#ffa502' } },
          { value: 17, name: '其他', itemStyle: { color: '#ff4757' } }
        ],
        label: {
          show: true,
          color: '#ffffff',
          formatter: '{b}: {c}%'
        }
      }]
    }
    
    categoryChart.setOption(categoryOption)
    await nextTick();
    categoryChart.resize();
    console.log('分类占比图表初始化成功')
    
  } catch (error) {
    console.error('分类占比图表初始化失败:', error)
  }
}

const initUserActivityChart = async (element) => {
  try {
    if (userActivityChart) {
      userActivityChart.dispose()
    }
    
    userActivityChart = echarts.init(element)
    
    const userActivityOption = {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(15, 52, 96, 0.9)',
        borderColor: '#00f0ff',
        borderWidth: 1,
        textStyle: { color: '#ffffff' }
      },
      legend: {
        data: ['PV', 'UV'],
        textStyle: { color: '#ffffff' },
        top: '5%'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '10%',
        top: '20%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        axisLine: { lineStyle: { color: '#00f0ff' } },
        axisLabel: { color: '#7ee9ff' }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#00f0ff' } },
        axisLabel: { color: '#7ee9ff' },
        splitLine: { lineStyle: { color: 'rgba(0, 240, 255, 0.1)' } }
      },
      series: [
        {
          name: 'PV',
          data: [8200, 9100, 7800, 9500, 10200, 8800, 7600],
          type: 'bar',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: '#00f0ff' },
                { offset: 1, color: 'rgba(0, 240, 255, 0.1)' }
              ]
            }
          }
        },
        {
          name: 'UV',
          data: [3200, 3800, 3100, 4200, 4800, 3600, 3000],
          type: 'bar',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: '#00ff9d' },
                { offset: 1, color: 'rgba(0, 255, 157, 0.1)' }
              ]
            }
          }
        }
      ]
    }
    
    userActivityChart.setOption(userActivityOption)
    await nextTick();
    userActivityChart.resize();
    console.log('用户活跃度图表初始化成功')
    
  } catch (error) {
    console.error('用户活跃度图表初始化失败:', error)
  }
}

// 分页切换函数
const startPagination = () => {
  pageTimer = setInterval(() => {
    currentPage.value = (currentPage.value + 1) % totalPages.value
  }, pageChangeInterval)
}



// 监听弹幕变化
watchEffect(() => {
  if (currentBarrage.value) {
    console.log('当前弹幕：', currentBarrage.value.text, '类型：', currentBarrage.value.type)
  }
})

function getWeekDay() {
  const days = ['日', '一', '二', '三', '四', '五', '六']
  return days[new Date().getDay()]
}

function refreshData() {
  // 刷新页面或重新拉取数据
  window.location.reload();
}

function exportData() {
  // 1. 核心指标
  const coreMetricsSheet = coreMetrics.value.map(item => ({
    指标: item.title,
    数值: item.prefix ? item.prefix + item.value : item.value,
    单位: item.unit,
    趋势: item.trend.text
  }));

  // 2. 热销商品
  const hotProductsSheet = hotProducts.value.map((item, idx) => ({
    排名: idx + 1,
    商品名: item.name,
    分类: item.category,
    销量: item.sales,
    增长率: item.growth + '%',
    营收: '¥' + (item.revenue / 10000).toFixed(1) + '万'
  }));

  // 3. 实时数据流
  const dataStreamsSheet = dataStreams.value.map(item => ({
    指标: item.label,
    数值: item.value,
    单位: item.unit
  }));

  // 创建工作簿
  const wb = XLSX.utils.book_new();

  // 添加每个sheet
  XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(coreMetricsSheet), "核心指标");
  XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(hotProductsSheet), "热销商品");
  XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(dataStreamsSheet), "实时数据流");

  // 导出
  const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
  saveAs(new Blob([wbout], { type: "application/octet-stream" }), "数据大屏报表.xlsx");
}

function toggleFullscreen() {
  // 切换全屏模式
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
  } else {
    document.exitFullscreen();
  }
}

const trendType = ref('day'); // 'day' | 'week' | 'month'

// 示例数据
const trendDataMap = {
  day: [1200, 900, 800, 1500, 2000, 2200, 2500, 2300, 2100, 1800, 1700, 1600, 1500, 1400, 1300, 1200, 1100, 1000, 900, 800, 700, 600, 500, 400],
  week: [12000, 15000, 18000, 17000, 16000, 20000, 22000],
  month: Array.from({ length: 30 }, (_, i) => 10000 + Math.round(Math.random() * 10000))
};
const trendXAxisMap = {
  day: Array.from({ length: 24 }, (_, i) => `${i}:00`),
  week: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  month: Array.from({ length: 30 }, (_, i) => `${i + 1}日`)
};

function changeTrendType(type) {
  trendType.value = type;
  updateTrendChart();
}
</script>

<style scoped>
/* 全局CSS变量 */
:root {
  --viewport-width: 100vw;
  --viewport-height: 100vh;
  --container-padding: 30px;
  --grid-gap: 20px;
  --font-size-base: 14px;
  --font-size-title: 18px;
  --font-size-large: 20px;
}

/* 基础样式 */
.dashboard-container {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #0c1e3a 0%, #1a237e 50%, #0c1e3a 100%);
  padding: var(--container-padding);
  color: #ffffff;
  font-family: 'Microsoft YaHei', 'Helvetica Neue', Arial, sans-serif;
  overflow-x: hidden;
  position: relative;
}

/* 动态字体尺寸 */
.section-title {
  color: #00f0ff;
  font-size: var(--font-size-title);
  font-weight: 600;
  margin: 0;
}

.stream-value {
  font-size: clamp(16px, 2vw, var(--font-size-large));
}

/* 头部样式 */
.dashboard-header {
  margin-bottom: 30px;
  position: relative;
  z-index: 10;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(15, 52, 96, 0.3);
  border-radius: 16px;
  padding: 24px 32px;
  border: 1px solid rgba(0, 240, 255, 0.2);
  backdrop-filter: blur(20px);
}

.header-left {
  flex: 1;
  position: relative;
}

.title-decoration {
  position: absolute;
  left: -15px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 60px;
}

.decoration-line {
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, 
    transparent 0%, 
    rgba(0, 240, 255, 0.3) 20%, 
    rgba(0, 240, 255, 0.8) 50%, 
    rgba(0, 240, 255, 0.3) 80%, 
    transparent 100%
  );
  border-radius: 2px;
  animation: decorationPulse 3s ease-in-out infinite;
  box-shadow: 0 0 8px rgba(0, 240, 255, 0.5);
}

.main-title {
  font-size: 32px;
  font-weight: 700;
  color: #00f0ff;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 36px;
  animation: float 3s ease-in-out infinite;
}

.subtitle {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
}

/* 中央区域样式 */
.header-center {
  flex: 2;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

/* 数据概览环样式 */
.data-ring {
  width: 120px;
  height: 120px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.ring-content {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 2px solid rgba(0, 240, 255, 0.3);
  background: radial-gradient(circle, rgba(0, 240, 255, 0.05), rgba(0, 240, 255, 0.02));
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  animation: ringRotate 20s linear infinite;
  box-shadow: 
    0 0 20px rgba(0, 240, 255, 0.2),
    inset 0 0 20px rgba(0, 240, 255, 0.1);
}

.center-logo {
  text-align: center;
  z-index: 2;
}

.logo-icon {
  font-size: 24px;
  margin-bottom: 4px;
  filter: drop-shadow(0 0 8px rgba(0, 240, 255, 0.5));
  animation: iconFloat 3s ease-in-out infinite;
}

.logo-text {
  font-size: 11px;
  color: #00f0ff;
  font-weight: 600;
  text-shadow: 0 0 8px rgba(0, 240, 255, 0.5);
  letter-spacing: 1px;
}

.header-right {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 24px;
  min-width: unset;
  height: auto;
  margin-bottom: 0;
}

/* 状态指示器样式 */
.status-indicators {
  display: flex;
  flex-direction: row;
  gap: 12px;
  margin-bottom: 0;
}

.status-card {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(0, 240, 255, 0.05);
  border: 1px solid rgba(0, 240, 255, 0.2);
  border-radius: 8px;
  padding: 8px 12px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  min-width: 110px;
}

.status-card:hover {
  background: rgba(0, 240, 255, 0.1);
  border-color: rgba(0, 240, 255, 0.4);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 240, 255, 0.2);
}

.status-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.status-label {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.6);
  font-weight: 500;
}

.status-value {
  font-size: 12px;
  color: #00f0ff;
  font-weight: 600;
}

/* 网络状态颜色 */
.network-status.network-good .status-value {
  color: #00ff9d;
}

.network-status.network-good .status-icon {
  filter: hue-rotate(120deg);
}

.network-status.network-normal .status-value {
  color: #ffa502;
}

.network-status.network-normal .status-icon {
  filter: hue-rotate(60deg);
}

.network-status.network-poor .status-value {
  color: #ff4757;
}

.network-status.network-poor .status-icon {
  filter: hue-rotate(300deg);
}

/* 时间区域样式 */
.time-section {
  text-align: left;
  margin-bottom: 0;
  min-width: 120px;
}

.current-time {
  font-size: 28px;
  font-weight: 600;
  color: #00f0ff;
  margin-bottom: 4px;
  text-shadow: 0 0 10px rgba(0, 240, 255, 0.3);
}

.date-display {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 2px;
}

.week-display {
  font-size: 12px;
  color: rgba(0, 255, 157, 0.8);
  font-weight: 500;
}

/* 快速操作按钮样式 */
.quick-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 8px;
  background: rgba(0, 240, 255, 0.1);
  border: 1px solid rgba(0, 240, 255, 0.3);
  color: #00f0ff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
}

.action-btn:hover {
  background: rgba(0, 240, 255, 0.2);
  border-color: rgba(0, 240, 255, 0.5);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 240, 255, 0.3);
}

.action-btn:active {
  transform: translateY(0);
}

.action-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.action-btn:hover::before {
  left: 100%;
}

.btn-icon {
  font-size: 16px;
  line-height: 1;
}

.refresh-btn:hover {
  background: rgba(0, 255, 157, 0.2);
  border-color: rgba(0, 255, 157, 0.5);
  color: #00ff9d;
}

.export-btn:hover {
  background: rgba(255, 165, 2, 0.2);
  border-color: rgba(255, 165, 2, 0.5);
  color: #ffa502;
}

.fullscreen-btn:hover {
  background: rgba(255, 71, 87, 0.2);
  border-color: rgba(255, 71, 87, 0.5);
  color: #ff4757;
}

/* 弹幕区域样式 */
.barrage-section {
  margin-bottom: 25px;
  position: relative;
  z-index: 10;
}

/* 弹幕系统样式 */
.barrage-container {
  height: 50px;
  overflow: hidden;
  position: relative;
  width: 100%;
  background: rgba(15, 52, 96, 0.15);
  border-radius: 25px;
  border: 1px solid rgba(0, 240, 255, 0.15);
  backdrop-filter: blur(8px);
  z-index: 50;
  display: flex;
  align-items: center;
}

.barrage-track {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.barrage-message {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  margin: auto 0;
  white-space: nowrap;
  will-change: transform;
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 32px 0 18px;
  border-radius: 25px;
  background: linear-gradient(90deg, rgba(0,255,255,0.85) 0%, rgba(0,240,255,0.25) 100%);
  box-shadow: 0 0 24px 4px rgba(0,240,255,0.18), 0 2px 16px 0 rgba(0,255,255,0.10);
  border: 1.5px solid rgba(0,255,255,0.25);
  backdrop-filter: blur(6px);
  transition: box-shadow 0.3s;
}

.barrage-message .message-icon {
  font-size: 22px;
  margin-right: 12px;
  filter: drop-shadow(0 0 6px #00f0ff88);
}

.barrage-message .message-text {
  font-size: 16px;
  font-weight: 700;
  color: #fff;
  letter-spacing: 0.5px;
  margin-right: 18px;
  text-shadow: 0 2px 8px rgba(0,240,255,0.12);
}

.barrage-message .message-time {
  font-size: 13px;
  color: #00f0ff;
  background: rgba(0,240,255,0.18);
  padding: 2px 14px;
  border-radius: 12px;
  font-weight: 600;
  margin-left: 8px;
  box-shadow: 0 0 8px rgba(0,240,255,0.18);
  border: 1px solid rgba(0,240,255,0.18);
}

.barrage-message.success {
  background: linear-gradient(90deg, rgba(0,255,157,0.85) 0%, rgba(0,240,255,0.3) 100%);
  border-color: #00ff9d;
  box-shadow: 0 0 20px rgba(0,255,157,0.5);
}

.barrage-message.achievement {
  background: linear-gradient(90deg, rgba(255,215,0,0.85) 0%, rgba(255,165,0,0.3) 100%);
  border-color: #ffd700;
  box-shadow: 0 0 20px rgba(255,215,0,0.5);
  color: #000;
}

.barrage-message.warning {
  background: linear-gradient(90deg, rgba(255,165,2,0.85) 0%, rgba(255,69,0,0.3) 100%);
  border-color: #ffa502;
  box-shadow: 0 0 20px rgba(255,165,2,0.5);
}

.barrage-message.info {
  background: linear-gradient(90deg, rgba(0,240,255,0.85) 0%, rgba(0,150,255,0.3) 100%);
  border-color: #00f0ff;
  box-shadow: 0 0 20px rgba(0,240,255,0.5);
}

.barrage-message.event {
  background: linear-gradient(90deg, rgba(255,71,87,0.85) 0%, rgba(255,20,147,0.3) 100%);
  border-color: #ff4757;
  box-shadow: 0 0 20px rgba(255,71,87,0.5);
}

.barrage-message:hover {
  animation-play-state: paused;
  box-shadow: 0 8px 32px rgba(0,240,255,0.4);
}

/* 指标卡片区域 */
.metrics-section {
  margin-bottom: 30px;
  position: relative;
  z-index: 10;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: clamp(15px, 2.5vw, 35px);
  /* 确保所有卡片等高 */
  align-items: stretch;
  width: 100%;
}

/* 图表区域 */
.charts-section {
  position: relative;
  z-index: 10;
  margin-bottom: 30px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 20px;
  min-height: 600px;
}

.chart-item {
  background: rgba(15, 52, 96, 0.3);
  border-radius: 12px;
  border: 1px solid rgba(0, 240, 255, 0.2);
  backdrop-filter: blur(10px);
  overflow: hidden;
  min-height: 400px;
}

.chart-large {
  grid-column: span 5;
}

.chart-medium {
  grid-column: span 4;
}

.chart-small {
  grid-column: span 3;
}

.chart-extra-small {
  grid-column: span 3;
}

.chart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.chart-header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.chart-title {
  color: #00f0ff;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.chart-indicators {
  display: flex;
  gap: 8px;
}

.indicator {
  padding: 4px 12px;
  background: rgba(0, 240, 255, 0.1);
  border: 1px solid rgba(0, 240, 255, 0.3);
  border-radius: 6px;
  color: #7ee9ff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
}

.indicator.active,
.indicator:hover {
  background: rgba(0, 240, 255, 0.3);
  color: #00f0ff;
}

.chart-content {
  flex: 1;
  min-height: 300px;
  height: 100%;
}

/* 分页指示器样式 */
.pagination-dots {
  display: flex;
  gap: 6px;
  align-items: center;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(0, 240, 255, 0.3);
  transition: all 0.3s ease;
  cursor: pointer;
}

.dot.active {
  background: #00f0ff;
  box-shadow: 0 0 8px rgba(0, 240, 255, 0.6);
  transform: scale(1.2);
}

/* 淡入动画 */
.fade-in {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.ranking-list {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 4px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: rgba(0, 240, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(0, 240, 255, 0.1);
  transition: all 0.3s ease;
  animation: slideInRight 0.6s ease-out both;
  position: relative;
  overflow: hidden;
  min-height: 65px;
  margin-bottom: 8px;
}

.ranking-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent, rgba(0, 240, 255, 0.03), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.ranking-item:hover {
  background: rgba(0, 240, 255, 0.1);
  transform: translateX(2px);
  border-color: rgba(0, 240, 255, 0.3);
}

.ranking-item:hover::before {
  opacity: 1;
}

.rank-number {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 12px;
  color: #fff;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.rank-1 { 
  background: linear-gradient(135deg, #ffd700, #ffed4e); 
  box-shadow: 0 2px 12px rgba(255, 215, 0, 0.4);
}
.rank-2 { 
  background: linear-gradient(135deg, #c0c0c0, #ddd); 
  box-shadow: 0 2px 12px rgba(192, 192, 192, 0.4);
}
.rank-3 { 
  background: linear-gradient(135deg, #cd7f32, #d4af37); 
  box-shadow: 0 2px 12px rgba(205, 127, 50, 0.4);
}
.rank-number:not(.rank-1):not(.rank-2):not(.rank-3) {
  background: linear-gradient(135deg, rgba(0, 240, 255, 0.3), rgba(0, 240, 255, 0.5));
}

.product-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 3px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.3;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3px;
  gap: 6px;
}

.product-category {
  color: rgba(0, 240, 255, 0.8);
  font-size: 11px;
  background: rgba(0, 240, 255, 0.1);
  padding: 2px 6px;
  border-radius: 10px;
  border: 1px solid rgba(0, 240, 255, 0.2);
  white-space: nowrap;
}

.product-sales {
  color: rgba(255, 255, 255, 0.7);
  font-size: 11px;
  font-weight: 500;
  white-space: nowrap;
}

.product-growth {
  font-size: 10px;
  font-weight: 600;
  line-height: 1;
}

.high-growth {
  color: #00ff9d;
}

.normal-growth {
  color: #ffa502;
}

.sales-metrics {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  min-width: 70px;
  flex-shrink: 0;
}

.sales-bar {
  width: 60px;
  height: 4px;
  background: rgba(0, 240, 255, 0.2);
  border-radius: 2px;
  overflow: hidden;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
}

.bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #00f0ff, #00ff9d);
  border-radius: 2px;
  transition: width 1s ease;
  position: relative;
}

.bar-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: shimmer 2s infinite;
}

.revenue-text {
  color: #00ff9d;
  font-size: 11px;
  font-weight: 600;
  white-space: nowrap;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

/* 排行榜滚动条美化 */
.ranking-list::-webkit-scrollbar {
  width: 3px;
}

.ranking-list::-webkit-scrollbar-track {
  background: rgba(0, 240, 255, 0.05);
  border-radius: 2px;
}

.ranking-list::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, rgba(0, 240, 255, 0.3), rgba(0, 255, 157, 0.3));
  border-radius: 2px;
}

.ranking-list::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, rgba(0, 240, 255, 0.5), rgba(0, 255, 157, 0.5));
}

/* 地图容器样式 */
.map-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: rgba(15, 52, 96, 0.3);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(0, 240, 255, 0.2);
  backdrop-filter: blur(10px);
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(0, 240, 255, 0.1);
}

.map-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
  margin-bottom: 4px;
}

.stat-value {
  color: #00ff9d;
  font-size: 16px;
  font-weight: 600;
}

.map-chart {
  flex: 1;
  min-height: 300px;
}

/* 数据流区域 */
.data-stream-section {
  position: relative;
  z-index: 10;
}

.stream-container {
  background: rgba(15, 52, 96, 0.3);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(0, 240, 255, 0.2);
  backdrop-filter: blur(10px);
}

.stream-title {
  color: #00f0ff;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  text-align: center;
}

.stream-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.stream-item {
  text-align: center;
  padding: 16px;
  border-radius: 8px;
  background: rgba(0, 240, 255, 0.05);
  border: 1px solid rgba(0, 240, 255, 0.1);
  transition: all 0.3s ease;
  animation: pulse 3s ease-in-out infinite;
}

.stream-item:hover {
  background: rgba(0, 240, 255, 0.1);
  transform: translateY(-2px);
}

.stream-label {
  display: block;
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
  margin-bottom: 4px;
}

.stream-value {
  display: block;
  color: #00f0ff;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 2px;
}

.stream-unit {
  display: block;
  color: rgba(255, 255, 255, 0.5);
  font-size: 10px;
}

/* 动画效果 */
@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
}

@keyframes dotPulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.5);
    opacity: 0.7;
  }
}

@keyframes decorationPulse {
  0%, 100% {
    opacity: 0.6;
    box-shadow: 0 0 8px rgba(0, 240, 255, 0.3);
  }
  50% {
    opacity: 1;
    box-shadow: 0 0 16px rgba(0, 240, 255, 0.8);
  }
}



/* 早期响应式规则 - 确保兼容性 */
@media (max-width: 1400px) {
  .chart-large { grid-column: span 8; }
  .chart-medium { grid-column: span 6; }
  .chart-small { grid-column: span 4; }
}

@media (max-width: 992px) {
  .chart-large,
  .chart-medium,
  .chart-small {
    grid-column: span 12;
  }
  
  .stream-content {
    flex-wrap: wrap;
    gap: 16px;
  }
}

.barrage-placeholder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: rgba(255, 255, 255, 0.5);
  font-size: 12px;
  font-style: italic;
  opacity: 0.7;
  animation: pulse 2s ease-in-out infinite;
}

/* 响应式设计 - 针对不同显示器尺寸优化 */

/* 4K 和超宽屏显示器 (2560px+) */
@media (min-width: 2560px) {
  .dashboard-container {
    padding: 40px;
  }
  
  .metrics-section {
    margin-bottom: 40px;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(5, 1fr);
  }
  
  .charts-grid {
    gap: 30px;
  }
  
  .section-title {
    font-size: 22px;
  }
  
  .stream-value {
    font-size: 24px;
  }
  
  /* 4K头部优化 */
  .main-title {
    font-size: 36px;
  }
  
  .title-icon {
    font-size: 40px;
  }
  
  .subtitle {
    font-size: 18px;
  }
  
  .data-ring {
    width: 140px;
    height: 140px;
  }
  
  .logo-icon {
    font-size: 28px;
  }
  
  .logo-text {
    font-size: 13px;
  }
  
  .indicator-item {
    transform: translate(-50%, -50%) rotate(var(--rotation)) translateY(-65px);
  }
  
  .indicator-dot {
    width: 8px;
    height: 8px;
  }
  
  .title-decoration {
    width: 5px;
    height: 80px;
    left: -20px;
  }
}

/* 2K 显示器 (1920px - 2559px) */
@media (min-width: 1920px) and (max-width: 2559px) {
  .dashboard-container {
    padding: 30px;
  }
  
  .metrics-section {
    margin-bottom: 35px;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(5, 1fr);
  }
  
  .charts-grid {
    gap: 25px;
  }
  
  /* 2K头部优化 */
  .main-title {
    font-size: 32px;
  }
  
  .title-icon {
    font-size: 36px;
  }
  
  .subtitle {
    font-size: 16px;
  }
  
  .data-ring {
    width: 130px;
    height: 130px;
  }
  
  .logo-icon {
    font-size: 26px;
  }
  
  .logo-text {
    font-size: 12px;
  }
  
  .indicator-item {
    transform: translate(-50%, -50%) rotate(var(--rotation)) translateY(-60px);
  }
  
  .title-decoration {
    width: 4px;
    height: 70px;
    left: -18px;
  }
}

/* 宽屏显示器 (1600px - 1919px) */
@media (min-width: 1600px) and (max-width: 1919px) {
  .metrics-section {
    margin-bottom: 32px;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(5, 1fr);
  }
  
  .chart-large { grid-column: span 5; }
  .chart-medium { grid-column: span 4; }
  .chart-small { grid-column: span 3; }
  .chart-extra-small { grid-column: span 3; }
}

/* 标准显示器 (1400px - 1599px) */
@media (min-width: 1400px) and (max-width: 1599px) {
  .metrics-section {
    margin-bottom: 30px;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(5, 1fr);
  }
  
  .chart-large { grid-column: span 5; }
  .chart-medium { grid-column: span 4; }
  .chart-small { grid-column: span 3; }
  .chart-extra-small { grid-column: span 3; }
}

/* 小尺寸显示器 (1200px - 1399px) */
@media (min-width: 1200px) and (max-width: 1399px) {
  .metrics-section {
    margin-bottom: 25px;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(4, 1fr);
  }
  
  .chart-large { grid-column: span 6; }
  .chart-medium { grid-column: span 6; }
  .chart-small { grid-column: span 4; }
  .chart-extra-small { grid-column: span 4; }
  
  .section-title {
    font-size: 16px;
  }
  
  .stream-value {
    font-size: 18px;
  }
}

/* 中等尺寸 (992px - 1199px) */
@media (min-width: 992px) and (max-width: 1199px) {
  .metrics-section {
    margin-bottom: 25px;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: clamp(12px, 2vw, 20px);
  }
  
  .chart-large { grid-column: span 8; }
  .chart-medium { grid-column: span 6; }
  .chart-small { grid-column: span 4; }
  .chart-extra-small { grid-column: span 4; }
  

}

/* 平板设备 (768px - 991px) */
@media (min-width: 768px) and (max-width: 991px) {
  .dashboard-container {
    padding: 20px;
  }
  
  .metrics-section {
    margin-bottom: 20px;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: clamp(10px, 2.5vw, 18px);
  }
  
  .chart-large,
  .chart-medium,
  .chart-small,
  .chart-extra-small {
    grid-column: span 12;
  }
  
  .stream-content {
    flex-wrap: wrap;
    gap: 16px;
  }
  
  /* 头部右侧响应式 */
  .header-right {
    min-width: 300px;
    gap: 15px;
  }
  
  .status-indicators {
    gap: 12px;
  }
  
  .status-card {
    min-width: 90px;
    padding: 6px 10px;
  }
  
  .current-time {
    font-size: 24px;
  }
  
  .data-ring {
    width: 100px;
    height: 100px;
  }
  
  .logo-icon {
    font-size: 20px;
  }
  
  .logo-text {
    font-size: 10px;
  }
  
  .indicator-item {
    transform: translate(-50%, -50%) rotate(var(--rotation)) translateY(-45px);
  }
  
  .title-decoration {
    width: 3px;
    height: 50px;
  }
}

/* 手机设备 (480px - 767px) */
@media (min-width: 480px) and (max-width: 767px) {
  .dashboard-container {
    padding: 15px;
  }
  
  .metrics-section {
    margin-bottom: 20px;
  }
  
  .metrics-grid {
    grid-template-columns: 1fr;
    gap: clamp(8px, 3vw, 15px);
  }
  
  .section-title {
    font-size: 14px;
  }
  
  .stream-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .stream-item {
    width: 100%;
    padding: 12px;
  }
  
  /* 手机端头部布局 */
  .header-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .header-center {
    order: 2;
  }
  
  .data-ring {
    width: 80px;
    height: 80px;
  }
  
  .logo-icon {
    font-size: 18px;
  }
  
  .logo-text {
    font-size: 9px;
  }
  
  .indicator-item {
    transform: translate(-50%, -50%) rotate(var(--rotation)) translateY(-35px);
  }
  
  .indicator-dot {
    width: 4px;
    height: 4px;
  }
  
  .title-decoration {
    display: none;
  }
  
  .header-right {
    order: 3;
    align-items: center;
    width: 100%;
    min-width: auto;
    gap: 12px;
  }
  
  .status-indicators {
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .status-card {
    min-width: 80px;
    padding: 6px 8px;
  }
  
  .time-section {
    text-align: center;
  }
  
  .current-time {
    font-size: 20px;
  }
  
  .quick-actions {
    justify-content: center;
  }
  
  .action-btn {
    width: 32px;
    height: 32px;
  }
}

/* 小屏手机 (最大479px) */
@media (max-width: 479px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .metrics-section {
    margin-bottom: 15px;
  }
  
  .metrics-grid {
    grid-template-columns: 1fr;
    gap: clamp(6px, 4vw, 12px);
  }
  
  .charts-grid {
    gap: 10px;
  }
  
  .chart-container {
    padding: 15px;
  }
  
  .stream-content {
    flex-direction: column;
    gap: 8px;
  }
  
  /* 小屏设备头部优化 */
  .header-content {
    padding: 16px 20px;
  }
  
  .main-title {
    font-size: 20px;
    text-align: center;
  }
  
  .title-icon {
    font-size: 24px;
  }
  
  .subtitle {
    font-size: 12px;
    text-align: center;
  }
  
  .status-indicators {
    gap: 6px;
  }
  
  .status-card {
    min-width: 70px;
    padding: 4px 6px;
  }
  
  .status-label {
    font-size: 9px;
  }
  
  .status-value {
    font-size: 10px;
  }
  
  .current-time {
    font-size: 18px;
  }
  
  .date-display,
  .week-display {
    font-size: 11px;
  }
  
  .action-btn {
    width: 28px;
    height: 28px;
  }
  
  .btn-icon {
    font-size: 14px;
  }
  
  .barrage-container {
    height: 40px;
    border-radius: 20px;
  }
  
  .barrage-message {
    padding: 6px 16px;
    font-size: 12px;
  }
}

/* 高DPI显示器优化 */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .dashboard-container {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
  
  .barrage-message {
    will-change: transform;
  }
  
  .chart-container {
    backface-visibility: hidden;
  }
}

/* 刷新率优化 */
@media (prefers-reduced-motion: no-preference) {
  .barrage-message {
    will-change: transform;
  }
}

/* 响应式设计 - 针对不同显示器尺寸优化 */
</style> 